package servlets;

import facebook.FacebookUserFilter;
import facebook.FacebookUtils;
import game.GameLogic;
import game.resources.Chat;
import game.resources.Profile;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.ecs.xml.XML;

import server.DBLogic;
import server.Room;
import server.resources.XMLFactory;

import com.google.code.facebookapi.FacebookException;
import com.google.code.facebookapi.FacebookJaxbRestClient;


public class GetRooms extends HttpServlet {
	private static final long serialVersionUID = 1L;
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	    DBLogic dbl = new DBLogic();
	    dbl.InitDBConnection();
	    
        response.setContentType("text/xml");
        response.setHeader("Cache-Control", "no-cache");
        
        String requestType = request.getParameter("type");
        
        XML resp = new XML("status");
	    
        try {
            if (requestType.equals("getCurrentRooms")) {
                String rooms = dbl.queryRooms();
                if (rooms != null) {
                    resp.addElement(rooms);
                } else {
                    resp.addElement("no-rooms");
                }
            } else if (requestType.equals("getRoomByID")) {
                String room = dbl.queryRoomState(Integer.parseInt(request.getParameter("roomID")));
                if (room != null) {
                    resp.addElement(room);
                } else {
                    resp.addElement("no-room");
                }
            } else if (requestType.equals("getHallOfFame")) {
                Map<Integer, List<Profile>> hof = dbl.getHallOfFame();
                String hofXML = XMLFactory.getHallOfFameXML(hof);
                resp.addElement(hofXML);
            } else {
                resp.addElement("bad-command");
            }
        } catch (SQLException e) {
            resp.addElement("db-problem");
        }
    
        response.getWriter().write(resp.toString());
        dbl.ShutDBConnection();
	}


    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	    DBLogic dbl = new DBLogic();
	    dbl.InitDBConnection();

	    response.setContentType("text/xml");
	    response.setHeader("Cache-Control", "no-cache");

	    String requestType = request.getParameter("type");
	    
	    XML resp = new XML("status");

	    FacebookJaxbRestClient client = FacebookUserFilter.getUserClientJaxb(request.getSession());
	    
	    try {
	        Profile user = FacebookUtils.getFacebookProfile(client);
	        
	        if (requestType.equals("createRoom")) {
	            
                Room room = new Room(user, 
                           Integer.parseInt(request.getParameter("gameSize")),
                           request.getParameter("gameName"));
                String roomState = XMLFactory.getRoomXML(room);
                int roomID = dbl.addNewRoom(roomState);
                dbl.addGameData("<status>pending</status>", roomID);
                resp.addElement("created");
                
                Cookie cookie = new Cookie("userID" , Long.toString(user.getUserID()));
                cookie.setPath("/");
                response.addCookie(cookie);

                cookie = new Cookie("roomID", Integer.toString(roomID));
                cookie.setPath("/");
                response.addCookie(cookie);
                
                cookie = new Cookie("playerIndex", "1");
                cookie.setPath("/");
                response.addCookie(cookie);
                
                dbl.updateGameNumberOfPlayers(roomID, 1);
                
                Chat chat = new Chat(roomID);
                chat.init();
                
	        } else if (requestType.equals("joinRoom")) {
	            int roomID = Integer.parseInt(request.getParameter("roomID"));
	            
	            String roomState = dbl.queryRoomState(roomID);
	            
	            Room room = XMLFactory.getRoomFromXML(roomState);
	            
	            if (room.getClientByID(user.getUserID()) != null) {
	                resp.addElement("already-connected");
	            } else {
    	            room.addToRoom(user);
    	            
	                Cookie cookie = new Cookie("userID" , Long.toString(user.getUserID()));
	                cookie.setPath("/");
	                response.addCookie(cookie);
	            
	                cookie = new Cookie("roomID", Integer.toString(roomID));
    	            cookie.setPath("/");
    	            response.addCookie(cookie);
    	            
                    cookie = new Cookie("playerIndex", Integer.toString(room.getNumOfPlayersInRoom()));
                    cookie.setPath("/");
                    response.addCookie(cookie);
                    
                    dbl.updateGameNumberOfPlayers(roomID, room.getNumOfPlayersInRoom());
    	            
    	            if (room.isFull()) {
    	                dbl.deleteRoom(roomID);
    	                GameLogic newGame = new GameLogic();
    	                newGame.init(roomID , room.getClients());
    	                dbl.updateGameData(roomID, XMLFactory.getGameDataXML(newGame.getGameData()), newGame.getGameData().getActionCounter());
    	            } else {
    	                roomState = XMLFactory.getRoomXML(room);
    	                dbl.updateRoom(roomID, roomState);	                
    	            }
    	            
    	            XML post = new XML("post");
    	            XML usernameXML = new XML("username");
    	            XML time = new XML("time");
    	            time.addElement(Long.toString(System.currentTimeMillis()));
    	            usernameXML.addElement("all");
    	            XML entry = new XML("entry");
    	            entry.addElement(user.getFullName() + " has joined the game (Rating: " + user.getRating() + ")");
    	            post.addElement(usernameXML);
    	            post.addElement(entry);
    	            post.addElement(time);
    	            dbl.postGameLog(roomID, post.toString());
    	            resp.addElement("joined");
	            }
	        } else {
	            resp.addElement("bad-command");
	        }
	    } catch (SQLException e) {
	        resp.addElement("db-problem");
	    } catch (FacebookException e) {
            resp.addElement("facebook-problem");
        }

	    response.getWriter().write(resp.toString());
	    dbl.ShutDBConnection();
	}
}
